<?php
/* 用户控制器, 处理后台管理端用户相关的请求 */

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Crypt;   //引入加密类

class SysUserController extends HomeController
{
    public function __construct(Request $request)
    {
        parent::__construct('login');
    }

    /* 登录接口 */
    public function login(Request $request)
    {
        //接受数据
        //$username = $request->input('username') ? : 'admin;select * from sys_user where id=2 limit 1';
        $username = $request->input('username');
        $password = $request->input('password');

        //要查询的字段
        $fiele = ['id', 'role_id', 'password', 'real_name','status'];
        //查询数据库
        $users = DB::table('sys_user')->where('username', $username)->select($fiele)->first();

        if (!$users) {
            $list['code'] = HTTP_ERROR;
            $list['message'] = '用户名或密码错误';
            return response()->json($list);
        }

        //判断状态
        if ($users->status == 0) {
            $list['code'] = HTTP_ERROR;
            $list['message'] = '用户已禁用';
            return response()->json($list);
        }

        //解密密码
        $decrypt_password = Crypt::decrypt($users->password);
        //判断密码是否正确
        if ($password != $decrypt_password) {
            $list['code'] = HTTP_ERROR;
            $list['message'] = '密码错误';
            return response()->json($list);
        }
        //删除数据中的密码字段
        unset($users->password);

        //生成token
        $users->token = $this->generateTimedToken(TOKEN_KEY . $users->id);
        $token_info = [
            'token' => $users->token,
            'user_id' => $users->id,
            'expired_time' => date('Y-m-d H:i:s', strtotime('+2 hours')),   //设置一个小时后过期
        ];
        //添加token到数据表
        DB::table('sys_token')->insert($token_info);

        //获取session下的_token，用于csrf验证
        $users->_token = $request->session()->get('_token');

        $list['code'] = HTTP_OK;
        $list['data'] = $users;
        $list['message'] = HTTP_OK_LOGINMSG;
        return response()->json($list);


        //验证数据
        /* $rules = [
            'username' => 'required|max:25',
            'password' => 'required|max:25',
        ];
        $validator = Validator::make($params, $rules, $this->validator_message);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        } */

    }




    /**
     * 生成带时间戳的签名Token
     * @param string $secret 加密密钥
     * @param int $expiry 过期时间(秒)
     * @return string 包含时间戳的Token
     */
    public static function generateTimedToken(string $secret): string {
        $header = base64_encode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
        $payload = base64_encode(json_encode(time()));
        $signature = hash_hmac('sha256', "$header.$payload", $secret);
        return "$header.$payload.$signature";
    }

}
